package com.fingard.dsp.bank.directbank;

import java.util.Date;
import java.util.HashMap;

import com.fingard.FGBiz;
import com.fingard.client.DspClient;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bankset.BankFront;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;

/**同步前置机登录会话，从主控服务器FGBiz.dspCenter.dspSet.masterServer获取*/
public class GetBfTokenFromMaster {

	protected static TransIDHelper tempTransID = new TransIDHelper(1, 9999);
	
	public GetBfTokenFromMaster(){
		sbLog = new StringBuilder();
	}
	
	public StringBuilder sbLog;
	
	/**执行会话同步，从主控服务获取前置机的登录会话token*/
	public HashMap<String,String> execGetToken(BankFront pBf,int timeoutSec){
		HashMap<String,String> map = new HashMap<String,String>();
		String respCode = "";
		String respInfo = "";
		String token = "";
		try{
			if(StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.masterServer)){
				respCode = "-1";
				respInfo = "未设置主控服务器masterServer地址";
			}
			Date nowDate = new Date();
			StringBuilder sbPck = new StringBuilder();
			sbPck.append("<ATSYH><TransReq><BankCode>"+pBf.bankCode+"</BankCode>");
			sbPck.append("<SystemCode>"+pBf.group+"</SystemCode>");
			sbPck.append("<Entity>"+pBf.corporation+"</Entity>");
			if(StringHelper.hasAnyChar(pBf.tenant)){
				sbPck.append("<Tenant>"+pBf.tenant+"</Tenant>");
			}
			sbPck.append("<TransType>GetBfToken</TransType>");
			sbPck.append("<TransSeqID>"+Format.DateTime12Year2Format.format(nowDate)+tempTransID.getNextIDStr()+"</TransSeqID>");
			sbPck.append("<TransTime>"+Format.DateTimeFormat.format(nowDate)+"</TransTime>");
			sbPck.append("<TransParam><BfCode>"+pBf.code+"</BfCode></TransParam></TransReq></ATSYH>");
			DspClient client = new DspClient(FGBiz.dspCenter.dspSet.masterServer);
			if(timeoutSec>0){
				client.timeoutSec = timeoutSec;
			}
			sbLog.append("发送获取会话报文："+sbPck.toString()+"\r\n");
			TcpReceiver retReceiver = client.sendMsg(sbPck.toString());
			if(retReceiver.isCompleted){
				String retXml = new String(retReceiver.recBytes, retReceiver.contentStartIndex,retReceiver.contentLength, retReceiver.charsetName);
				sbLog.append("获取会话响应报文："+retXml+"\r\n");
				XmlTextReader reader = new XmlTextReader(retXml);
				respCode = reader.getSimpleTextNotNull("RespCode");
				respInfo = reader.getSimpleTextNotNull("RespInfo");
				token = reader.getSimpleTextNotNull("Token");
			}else{
				respCode = "-1";
				respInfo = retReceiver.connState+"-"+retReceiver.getConnMsg();
				FGBiz.limitMsg.error(pBf.bankCode+".SyncBfToken", respInfo);
				sbLog.append("获取会话失败："+respInfo+"\r\n");
			}
		}catch(Throwable e){
			FGBiz.limitMsg.exception(pBf.bankCode+".SyncBfToken", e, pBf.code);
			respInfo = LogHelper.getStackTrace(e);
			sbLog.append("获取会话异常："+respInfo+"\r\n");
		}
		map.put("respCode", respCode);
		map.put("respInfo", respInfo);
		map.put("token", token);
		return map;
	}
}
